package com.lengxf.mybatis.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.lengxf.mybatis.*.ckMapper"}, sqlSessionFactoryRef = "ckSqlSessionFactory")
public class CkDataSourceConfigure {

    @Bean("ckDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.ck")
    public DataSource ckDataSource() {
        return UserHikariConfig.build();
    }

    @Bean(name = "ckSqlSessionFactory")
    public SqlSessionFactory ckSqlSessionFactory(@Qualifier("ckDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.lengxf.mybatis.**.ckEntity");
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper*/mysql/*.xml"));
        bean.setPlugins(mysqlInterceptor());
        bean.setConfiguration(MybatisConfig.build(false));
        return bean.getObject();
    }

    /**
     * 此方法不可注入为bean
     * 需要为每个数据源单独配置插件
     *
     * @Author Lengxf
     */
    private MybatisPlusInterceptor mysqlInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.CLICK_HOUSE));
        return interceptor;
    }

    @Bean(name = "ckSqlSessionTemplate")
    public SqlSessionTemplate ckSqlSessionTemplate(@Qualifier("ckSqlSessionFactory") SqlSessionFactory ckSqlSessionFactory) {
        return new SqlSessionTemplate(ckSqlSessionFactory);
    }


}
